package com.atguigu.gmall.weball.controller;


import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.cart.CartFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CartController {

    //http://cart.gmall.com/addCart.html?skuId=54&skuNum=1&sourceType=query

    @Autowired
    CartFeignClient cartFeignClient;

    //SpringMVC每次接到请求以后，自己会把请求放到ThreadLocal中。
//    public static ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<>();
    /**
     * 把商品添加到购物车
     * @param skuId
     * @return
     */
    @GetMapping("/addCart.html")
    public String cartPage(@RequestParam("skuId") Long skuId,
                           @RequestParam(value = "skuNum",defaultValue = "1")Integer skuNum,
                           Model model,
                           @RequestHeader(value=RedisConstant.USER_ID_REQUEST_HEADER,required = false)
                                       String userId,
                           @RequestHeader(value=RedisConstant.TEMP_USER_ID_HEADER,required = false)
                                       String userTempId){
        System.out.println("web-all：userId"+userId);
        System.out.println("web-all：userTempId"+userTempId);


        System.out.println("web-all：线程："+Thread.currentThread().getName());
        //前端还会带上临时id；  userTempId
        //TODO  调用远程购物车服务把当前 skuId ，添加到 临时/用户 购物车中
        Result result = cartFeignClient.addSkuToCart(skuId, skuNum);
        if(result.isOk()){
            Object data = result.getData();
            //skuinfo: skuDefaultImg、skuName、id、
            model.addAttribute("skuInfo",data);
            model.addAttribute("skuNum",skuNum);
        }else {
            String message = result.getMessage();
            model.addAttribute("msg",message);
            return "cart/addCarterror";
        }


        //返回购物车添加成功的页面
        return "cart/addCart";
    }


    @GetMapping("/cart.html")
    public String cartListPage(){


        return "cart/index"; //返回购物车列表页
    }
}
